package com.obrock;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Дмитрий Г. Кузнецов
 * Date: 22.10.12
 * Time: 16:28
 * To change this template use File | Settings | File Templates.
 */
public class MessageThread implements Runnable {

    static final long VIEW_DEPTH = (new Date().getTime() - 7 * 24 * 60 * 60 * 1000);

    final Handler myHandler = new Handler();
    public static final Object messageReceived = new Object();
    public static Map<String, String> messages = new HashMap<String, String>(0);
    private Thread thread;
    private static Database db = null;
    private Context context = null;
    public static boolean terminate = false;
    public static boolean enabled = false;


    public MessageThread(Context context) {
        db = new Database(context);
        this.context = context;

        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        try {
            while (!terminate) {

                synchronized (messageReceived) {
                    messageReceived.wait(context.getSharedPreferences(Main.PREFERENCES_NAME, 0).getLong("SYNC_PERIOD", 600000));
                }

                if (terminate) {
                    break;
                }

                if (!enabled) {
                    continue;
                }

                if (messages.size() > 0) {
                    for (Map.Entry<String, String> m : messages.entrySet()) {
                        String from = m.getKey();
                        String message = m.getValue();

                        if (db.findRemark(message) == null) {
                            processMessage(from, message);
                        }
                    }
                    messages.clear();
                }


                long time = context.getSharedPreferences(Main.PREFERENCES_NAME, 0).getLong("LAST_MESSAGE", VIEW_DEPTH);
                long start = time;
                Cursor cursor = context.getContentResolver().query(
                        Uri.parse("content://sms/inbox"),
                        new String[]{"address", "date", "date_sent", "body"},
                        "date > ?",
                        new String[]{"" + time},
                        "date ASC");

                if (cursor.moveToFirst()) {
                    do {
                        String from = cursor.getString(0);
                        String message = cursor.getString(3);
                        time = cursor.getLong(1);

                        if (db.findRemark(message) == null) {
                            processMessage(from, message);
                        }

                    } while (cursor.moveToNext());
                }

                if (time > start) {
                    SharedPreferences prefs = context.getSharedPreferences(Main.PREFERENCES_NAME, 0);
                    SharedPreferences.Editor edit = prefs.edit();
                    edit.putLong("LAST_MESSAGE", time);
                    edit.commit();
                }

                ////////

            }
        } catch (InterruptedException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    void processMessage(String from, String text) {
        Balance[] templates = db.getTemplates();
        boolean success = false;

        Log.d(Main.LOG_TAG, "SMS: " + from);
        Log.d(Main.LOG_TAG, "SMS: " + text);
        for (Balance t : templates) {
            MessageTemplate x = new MessageTemplate(t.template);
            if (t.number.length() > 0 && !from.equals(t.number)) {
                continue;
            }

            if (x.parse(text)) {
                if (t.key.length() > 0 && !x.key.equals(t.key)) {
                    continue;
                }

                Log.d(Main.LOG_TAG, "SMS Parsing success");


                t.amount = x.amount;
                t.name = x.title;
                t.date = x.date;
                t.remark = text;
                t.mode = Balance.MODE_NORMAL;
                t.parentID = t.balanceID;
                t.flags |= Balance.FLAG_INHERIT_TEMPLATE;

                if (t.name.trim().length() == 0) {
                    t.name = context.getResources().getString(R.string.transaction);
                }

                if (t.date.getYear() < 2000) {
                    t.date.setYear(new Date().getYear());
                }

                if (x.amount == 0) {
                    if (x.foreign != 0 && x.course != 0) {
                        x.amount = x.foreign * x.course;
                    } else if (x.foreign == 0 && x.course != 0) {
                        x.amount = x.amount * x.course;
                    }
                }

                if ((t.flags & Balance.FLAG_FORCE_TRANSFER) != 0) {
                    t.mode = Balance.MODE_NORMAL;
                } else {
                    t.mode = Balance.MODE_PROGNOSIS;
                    t.flags &= ~0x00FF;
                    t.flags |= Balance.FLAG_PERIOD_ONCE;
                }

                Log.d(Main.LOG_TAG, "SMS Parsed: amount " + t.amount);
                Log.d(Main.LOG_TAG, "SMS Parsed: name " + t.name);
                Log.d(Main.LOG_TAG, "SMS Parsed: date " + t.date);

                t.append();
                Log.d(Main.LOG_TAG, "SMS Processed successfully");


                String notify = "";
                if (t.accountFrom != null) {
                    notify = String.format("%s %s: %.2f %s",
                            context.getResources().getString(R.string.outbound),
                            t.accountFrom.name,
                            t.amount,
                            x.currency);
                } else if (t.accountTo != null) {
                    notify = String.format("%s %s: %.2f %s",
                            context.getResources().getString(R.string.inbound),
                            t.accountTo.name,
                            t.amount,
                            x.currency);
                }
                Log.d(Main.LOG_TAG, "Notify:" + notify);
                Main.showNotification(context, notify);

                success = true;
            }
        }

        if (success) {
            myHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (Main.context != null) {
                        Main.setMode(Main.viewMode);
                    }
                }
            });
        }
    }

    public static void enable() {
        enabled = true;
    }

    public static void disable() {
        enabled = false;
    }

    public static void force() {
        synchronized (messageReceived) {
            messageReceived.notify();
        }
    }
}

